class Recorder {
  constructor(props) {
    this.canvas = props.canvas
    this.frameRate = props.frameRate || 15
    this.mediaRecorder = null
    this.chunks = []
  }

  /**
   * 开始录制
   */
  start() {
    console.log('Recording started')
    const stream = this.canvas.captureStream(this.frameRate)
    this.mediaRecorder = new MediaRecorder(stream, {
      mimeType: 'video/webm; codecs=vp9'
    })
    this.mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        this.chunks.push(event.data)
      }
    }
    this.mediaRecorder.start()
  }

  /**
   * 停止录制
   * @returns Promise<Blob | null>
   */
  stop() {
    console.log('Recording stopped')
    return new Promise((resolve) => {
      if (this.mediaRecorder) {
        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.chunks, { type: 'video/webm' })
          resolve(blob)
        }
        this.mediaRecorder.stop()
      } else {
        resolve(null)
      }
    })
  }
}

export default Recorder
